package com.sxx.mallcart.service.Impl;

import com.alibaba.fastjson.JSON;
import com.sxx.commons.constant.CartConstant;
import com.sxx.commons.utils.R;
import com.sxx.commons.vo.MemberVO;
import com.sxx.mallcart.feign.ProductFeignService;
import com.sxx.mallcart.interceptor.AuthIntercepter;
import com.sxx.mallcart.service.ICartService;
import com.sxx.mallcart.vo.Cart;
import com.sxx.mallcart.vo.CartItem;
import com.sxx.mallcart.vo.SkuInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**购物车信息是存储在redis中的
 * @Auther: sunxx
 * @Date: 2024/8/29 - 08 - 29 - 0:24
 * @Description: com.sxx.mallcart.service.Impl
 * @version: 1.0
 */
@Service
public class ICartServiceImpl implements ICartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    /**
     * 查询当前用户的购物车信息
     * @return
     */
    @Override
    public Cart getCartList() {

        BoundHashOperations<String, Object, Object> operation = getCartKeyOperation();//getCartKeyOperation()没登录memberVO为空报空指针异常
        Cart cart = new Cart();
        if (operation == null){
            cart.setItems(null);
            return null;
        }
        Set<Object> keys = operation.keys();
        List<CartItem> cartItems = new ArrayList<>();
        for (Object k : keys) {
            String key = (String) k;
            Object o = operation.get(key);
            String json = (String) o;
            CartItem item = JSON.parseObject(json, CartItem.class);
            cartItems.add(item);
        }
        cart.setItems(cartItems);
        return cart;
    }

    /**
     * 商品添加到购物车中
     * @param skuId
     * @param proNum
     * @return
     */
    @Override
    public CartItem addCart(Long skuId, Integer proNum) throws Exception {
        BoundHashOperations<String, Object, Object> cartKeyOperation = getCartKeyOperation();
        //如果没有登录
        if (skuId == null){
            return null;
        }
        //如果redis中已经存储了该商品，那么只需要修改商品数量就可以了

        Object o = cartKeyOperation.get(skuId.toString());
        if (o != null){
            //存在该商品，修改数量
            String json = (String) o;
            CartItem item = JSON.parseObject(json, CartItem.class);
            item.setCount(item.getCount()+proNum);
            cartKeyOperation.put(skuId.toString(),JSON.toJSONString(item));
            return item;
        }
        CartItem item = new CartItem();
        CompletableFuture future1 = CompletableFuture.runAsync(() -> {
            //1远程调用获取商品信息
            R r = productFeignService.info(skuId);
            String skuInfoJSON = (String)r.get("skuInfoJSON");
            SkuInfoVO skuInfo = JSON.parseObject(skuInfoJSON,SkuInfoVO.class) ;
            item.setCheck(true);
            item.setCount(proNum);
            item.setImage(skuInfo.getSkuDefaultImg());
            item.setPrice(skuInfo.getPrice());
            item.setSkuId(skuId);
            item.setTitle(skuInfo.getSkuTitle());
            item.setSpuId(skuInfo.getSpuId());
        },threadPoolExecutor);

        CompletableFuture future2 = CompletableFuture.runAsync(() -> {
            //2获取商品销售属性
            List<String> skuSaleAttrs = productFeignService.getSkuSaleAttrs(skuId);
            item.setSkuAttr(skuSaleAttrs);
        }, threadPoolExecutor);

        CompletableFuture.allOf(future1,future2).get();
        //3把数据存在redis中
        String json = JSON.toJSONString(item);
        cartKeyOperation.put(skuId.toString(),json);
        return item;
    }

    /*
    * 查询所有当前用户的购物车内选中的提交确认的商品信息
    * */
    @Override
    public List<CartItem> getCartToConfirm() {
        BoundHashOperations<String, Object, Object> cartKeyOperation = getCartKeyOperation();
        List<Object> values = cartKeyOperation.values();
        List<CartItem> collect = values.stream().map(item -> {
            String json = (String) item;
            CartItem cartItem = JSON.parseObject(json, CartItem.class);
            return cartItem;
        }).filter(item ->{
            return item.isCheck();
        }).collect(Collectors.toList());
        return collect;
    }

    private BoundHashOperations<String, Object, Object> getCartKeyOperation() {
        //hash key: cart:1 skuId:cartItem
        MemberVO memberVO = AuthIntercepter.threadLocal.get();
        if (memberVO == null){
            return null;
        }
        String cartKey = CartConstant.CART_PREFIX + memberVO.getId();//getCartKeyOperation()没登录memberVO为空报空指针异常
        BoundHashOperations<String, Object, Object> hashOperations = redisTemplate.boundHashOps(cartKey);
        return hashOperations;
    }
}
